
<template>
  <div class="panel-tab__content">
    <template v-if="handleId === '1'">
      <el-table :data="dataList"
        max-height="240"
        border
        fit>
        <el-table-column label="校验类型"
          width="85px"
          align="center"
          show-overflow-tooltip
          :formatter="(row)=>handleCheckTypeOptions(row)">
        </el-table-column>
        <el-table-column label="校验条件"
          align="center"
          prop="label"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作"
          align="center"
          width="60px">
          <template v-slot="{ row, $index }">
            <!-- <el-button link
            @click="openAttributesForm(row, $index)">编辑</el-button>
          <el-divider direction="vertical" /> -->
            <el-button link
              type="danger"
              @click="removeAttributes(row, $index,'1')">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="element-drawer__button">
        <el-button type="primary"
          :icon="Plus"
          @click="openAttributesForm(null, -1)">添加条件配置</el-button>
      </div>
      <vxe-modal v-model="propertyFormModelVisible"
        title="条件配置"
        width="40%"
        height="50%"
        resize
        mask-closable
        show-footer
        show-zoom
        destroyOnClose
        @hide="propertyFormModelVisible = false"
        @close="propertyFormModelVisible = false">
        <el-form :model="propertyForm"
          label-width="100px"
          ref="propertiesRef"
          @submit.prevent>
          <el-form-item label="校验类型："
            prop="name"
            :rules="[{ required: true, trigger: ['blur', 'change'],message:'请选择校验类型' }]">
            <el-select v-model="propertyForm.name"
              style="width: 100%"
              placeholder="请选择校验类型"
              clearable>
              <el-option v-for="item in checkTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="校验条件："
            prop="value"
            :rules="[{ required: true, trigger: ['blur', 'change'], message:'请选择校验条件'}]">
            <el-tree-select v-model="propertyForm.value"
              :data="treeData"
              :props="defaultProps"
              placeholder="请选择校验条件"
              default-expand-all />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary"
            @click="saveAttribute()">确定</el-button>
          <el-button @click="propertyFormModelVisible = false">取消</el-button>
        </template>
      </vxe-modal>
    </template>
    <template v-else-if="handleId === '2'">
      <el-table :data="preList"
        max-height="240"
        border
        fit>
        <el-table-column label="执行类型"
          width="85px"
          align="center"
          show-overflow-tooltip
          :formatter="(row)=>handleCheckTypeOptions(row)">
        </el-table-column>
        <el-table-column label="执行规则"
          align="center"
          prop="label"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作"
          align="center"
          width="60px">
          <template v-slot="{ row, $index }">
            <!-- <el-button link
            @click="openAttributesForm(row, $index)">编辑</el-button>
          <el-divider direction="vertical" /> -->
            <el-button link
              type="danger"
              @click="removeAttributes(row, $index,'2')">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="element-drawer__button">
        <el-button type="primary"
          :icon="Plus"
          @click="openAttributesForm(null, -1)">添加前置配置</el-button>
      </div>
      <vxe-modal v-model="propertyPreFormModelVisible"
        title="前置配置"
        width="40%"
        height="50%"
        resize
        mask-closable
        show-footer
        show-zoom
        destroyOnClose
        @hide="propertyPreFormModelVisible = false"
        @close="propertyPreFormModelVisible = false">
        <el-form :model="propertyPreForm"
          label-width="100px"
          ref="propertiesRef"
          @submit.prevent>
          <el-form-item label="执行类型："
            prop="name"
            :rules="[{ required: true, trigger: ['blur', 'change'],message:'请选择执行类型' }]">
            <el-select v-model="propertyPreForm.name"
              style="width: 100%"
              placeholder="请选择执行类型"
              clearable>
              <el-option v-for="item in checkTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="执行规则："
            prop="value"
            :rules="[{ required: true, trigger: ['blur', 'change'], message:'请选择执行规则'}]">
            <el-tree-select v-model="propertyPreForm.value"
              :data="treeData"
              :props="defaultProps"
              placeholder="请选择执行规则"
              default-expand-all />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary"
            @click="saveAttribute()">确定</el-button>
          <el-button @click="propertyPreFormModelVisible = false">取消</el-button>
        </template>
      </vxe-modal>
    </template>
    <template v-else-if="handleId === '3'">
      <el-table :data="postList"
        max-height="240"
        border
        fit>
        <el-table-column label="执行类型"
          width="85px"
          align="center"
          show-overflow-tooltip
          :formatter="(row)=>handleCheckTypeOptions(row)">
        </el-table-column>
        <el-table-column label="执行规则"
          align="center"
          prop="label"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作"
          align="center"
          width="60px">
          <template v-slot="{ row, $index }">
            <!-- <el-button link
            @click="openAttributesForm(row, $index)">编辑</el-button>
          <el-divider direction="vertical" /> -->
            <el-button link
              type="danger"
              @click="removeAttributes(row, $index,'3')">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="element-drawer__button">
        <el-button type="primary"
          :icon="Plus"
          @click="openAttributesForm(null, -1)">添加后置配置</el-button>
      </div>
      <vxe-modal v-model="propertyPostFormModelVisible"
        title="后置配置"
        width="40%"
        height="50%"
        resize
        mask-closable
        show-footer
        show-zoom
        destroyOnClose
        @hide="propertyPostFormModelVisible = false"
        @close="propertyPostFormModelVisible = false">
        <el-form :model="propertyPostForm"
          label-width="100px"
          ref="propertiesRef"
          @submit.prevent>
          <el-form-item label="执行类型："
            prop="name"
            :rules="[{ required: true, trigger: ['blur', 'change'],message:'请选择执行类型' }]">
            <el-select v-model="propertyPostForm.name"
              style="width: 100%"
              placeholder="请选择执行类型"
              clearable>
              <el-option v-for="item in checkTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="执行规则："
            prop="value"
            :rules="[{ required: true, trigger: ['blur', 'change'], message:'请选择执行规则'}]">
            <el-tree-select v-model="propertyPostForm.value"
              :data="treeData"
              :props="defaultProps"
              placeholder="请选择执行规则"
              default-expand-all />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary"
            @click="saveAttribute()">确定</el-button>
          <el-button @click="propertyPostFormModelVisible = false">取消</el-button>
        </template>
      </vxe-modal>
    </template>
    <template v-else>
      <el-table :data="busiList"
        max-height="240"
        border
        fit>
        <el-table-column label="执行类型"
          width="85px"
          align="center"
          show-overflow-tooltip
          :formatter="(row)=>handleCheckTypeOptions(row)">
        </el-table-column>
        <el-table-column label="执行规则"
          align="center"
          prop="label"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作"
          align="center"
          width="60px">
          <template v-slot="{ row, $index }">
            <!-- <el-button link
            @click="openAttributesForm(row, $index)">编辑</el-button>
          <el-divider direction="vertical" /> -->
            <el-button link
              type="danger"
              @click="removeAttributes(row, $index,'4')">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="element-drawer__button">
        <el-button type="primary"
          :icon="Plus"
          @click="openAttributesForm(null, -1)">添加业务配置</el-button>
      </div>
      <vxe-modal v-model="propertyBusiFormModelVisible"
        title="业务配置"
        width="40%"
        height="50%"
        resize
        mask-closable
        show-footer
        show-zoom
        destroyOnClose
        @hide="propertyBusiFormModelVisible = false"
        @close="propertyBusiFormModelVisible = false">
        <el-form :model="propertyBusiForm"
          label-width="100px"
          ref="propertiesRef"
          @submit.prevent>
          <el-form-item label="执行类型："
            prop="name"
            :rules="[{ required: true, trigger: ['blur', 'change'],message:'请选择执行类型' }]">
            <el-select v-model="propertyBusiForm.name"
              style="width: 100%"
              placeholder="请选择执行类型"
              clearable>
              <el-option v-for="item in checkTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="执行规则："
            prop="value"
            :rules="[{ required: true, trigger: ['blur', 'change'], message:'请选择执行规则'}]">
            <el-tree-select v-model="propertyBusiForm.value"
              :data="treeData"
              :props="defaultProps"
              placeholder="请选择执行规则"
              default-expand-all />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary"
            @click="saveAttribute()">确定</el-button>
          <el-button @click="propertyBusiFormModelVisible = false">取消</el-button>
        </template>
      </vxe-modal>
    </template>
  </div>
</template>
<script>
import { Plus } from '@element-plus/icons-vue'
import { useWorkflowApi } from '@/api/index';
import { useUserInfo } from '/@/stores/modules';
const { postValidationList, postProcessHandlerList } = useWorkflowApi()
const { userInfos } = useUserInfo();
export default {
  name: "ElementProperties",
  setup() {
    return {
      Plus
    }
  },
  props: {
    id: String,
    type: String,
    handleId: String,
  },
  inject: {
    prefix: "prefix",
    width: "width",
    bpmnState: 'bpmnState',
  },
  data() {
    return {
      elementPropertyList: [],
      propertyForm: {},
      propertyPreForm: {},
      propertyPostForm: {},
      propertyBusiForm: {},
      editingPropertyIndex: -1,
      propertyFormModelVisible: false,
      propertyPreFormModelVisible: false,
      propertyPostFormModelVisible: false,
      propertyBusiFormModelVisible: false,
      checkTypeOptions: [
        {
          label: "送审",
          value: '1'
        },
        {
          label: "审核",
          value: '2'
        },
        {
          label: "撤销",
          value: '3'
        },
        {
          label: "退回",
          value: '4'
        },
      ],
      checkConditionOptions: [
        {
          label: "审核条件",
          value: 1
        },
        {
          label: "撤销条件",
          value: 2
        },
        {
          label: "退回条件",
          value: 3
        },
      ],
      dataList: [],//条件校验配置
      preList: [], // 前置处理配置
      busiList: [], // 业务处理配置
      postList: [], // 后置
      item: undefined,
      treeData: [],
      defaultProps: { // 默认
        children: 'children',
        label: 'name',
        value: 'id'
      },
    };
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        val && val.length && this.resetAttributesList();
      }
    },
  },
  methods: {
    async getTreeData() {
      const actionTypeMap = {
        '1': undefined, //条件校验
        '2': 0,//前置校验
        '3': 1,//后置校验
        '4': 2//业务校验
      };
      const actionType = actionTypeMap[this.handleId] ?? undefined;
      const { adCode } = userInfos;
      // const adCode = ''
      const result = this.handleId === '1'
        ? await postValidationList({ actionType, adCode })
        : await postProcessHandlerList({ actionType, adCode });
      this.treeData = result.data;
    },
    handleCheckTypeOptions(row) {
      let title = ''
      this.checkTypeOptions.forEach((item) => {
        if (item.value === row.name) {
          title = item.label
        }
      })
      return title
    },
    handleCheckConditionOptions(val) {
      this.item = {}
      this.dataList = []
      this.preList = []
      this.busiList = []
      this.postList = []
      if (val && val.length) {
        let obj = {}
        val.forEach((element, index) => {
          this.handleFindItem(this.treeData, element)
          if (this.item) {
            obj = {
              ...element,
              label: this.item.name
            }
          }
          switch (element.id) {
            case '1'://条件校验
              this.dataList.push(obj)
              break;
            case '2'://前置处理
              this.preList.push(obj)
              break;
            case '3'://后置处理
              this.postList.push(obj)
              break;
            case '4'://业务处理
              this.busiList.push(obj)
              break;
            default:
              break;
          }
        })
      }
    },
    // 循环遍历寻找
    handleFindItem(array, row) {
      for (const key in array) {
        if (Object.hasOwnProperty.call(array, key)) {
          const item = array[key];
          if (row && item.id === row.value) {
            this.item = item
            break
          } else {
            if (item.children && item.children.length > 0) {
              this.handleFindItem(item.children, row)
            }
          }
        }
      }
    },
    /**
     * 初始化属性列表
     */
    async resetAttributesList() {
      await this.getTreeData()
      this.$nextTick(() => {
        switch (this.handleId) {
          case '1': //条件配置
            this.propertyForm = {}
            break;
          case '2': // 前置处理
            this.propertyPreForm = {}
            break;
          case '3': // 后置处理
            this.propertyPostForm = {}
            break;
          case '4': // 业务处理
            this.propertyBusiForm = {}
            break;
          default:
            break;
        }
      });
      this.bpmnElement = window.bpmnInstances.bpmnElement;
      this.otherExtensionList = []; // 其他扩展配置
      this.bpmnElementProperties = this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
        if (ex.$type !== `${this.prefix}:Properties`) {
          this.otherExtensionList.push(ex);
        }
        return ex.$type === `${this.prefix}:Properties`;
      }) ?? [];
      this.bpmnState.propertyList = this.bpmnElementProperties.reduce((pre, current) => {
        return current.values ? pre.concat(current.values) : pre
      }, []);
      this.elementPropertyList = JSON.parse(JSON.stringify(this.bpmnState.propertyList ?? []));
      this.handleCheckConditionOptions(this.elementPropertyList)
    },
    // 打开界面
    openAttributesForm(attr, index) {
      this.resetAttributesList()
      this.editingPropertyIndex = index;
      switch (this.handleId) {
        case '1':
          this.propertyForm = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
          this.propertyFormModelVisible = true;
          break;
        case '2': // 前置处理
          this.propertyPreForm = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
          this.propertyPreFormModelVisible = true;
          break;
        case '3': // 后置处理
          this.propertyPostForm = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
          this.propertyPostFormModelVisible = true;
          break;
        case '4': // 业务处理
          this.propertyBusiForm = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
          this.propertyBusiFormModelVisible = true;
          break;
        default:
          break;
      }
      // this.propertyForm = index === -1 ? {} : JSON.parse(JSON.stringify(attr));

      this.$nextTick(() => {
        if (this.$refs["attributeFormRef"]) this.$refs["attributeFormRef"].clearValidate();
      });
    },
    removeAttributes(attr, index, id) {
      this.$confirm("确认移除该检验条件配置吗？", "提示", {
        confirmButtonText: "确 认",
        cancelButtonText: "取 消"
      })
        .then(() => {
          // 根据 id 找到并删除元素
          const itemIndex = this.elementPropertyList.findIndex((item) => item.id === id && item.value === attr.value);
          if (itemIndex !== -1) {
            this.elementPropertyList.splice(itemIndex, 1);
          }
          switch (id) {
            case '1': // 条件校验
              // const dataIndex = this.dataList.findIndex((item) => item.value === attr.value);
              // if (dataIndex !== -1) {
              //   this.dataList.splice(dataIndex, 1);
              // }
              this.dataList.splice(index, 1)
              break;
            case '2': // 前置处理
              // const preIndex = this.preList.findIndex((item) => item.value === attr.value);
              // if (preIndex !== -1) {
              //   this.preList.splice(preIndex, 1);
              // }
              this.preList.splice(index, 1);
              break;
            case '3': // 后置处理
              // const postIndex = this.postList.findIndex((item) => item.value === attr.value);
              // if (postIndex !== -1) {
              //   this.postList.splice(postIndex, 1);
              // }
              this.postList.splice(index, 1);
              break;
            case '4': // 业务处理
              // const busiIndex = this.busiList.findIndex((item) => item.value === attr.value);
              // if (busiIndex !== -1) {
              //   this.busiList.splice(busiIndex, 1);
              // }
              this.busiList.splice(index, 1);
              break;
            default:
              break;
          }
          const elementIndex = this.bpmnState.propertyList.findIndex((item) => item.id === id && item.value === attr.value);
          if (elementIndex !== -1) {
            this.bpmnState.propertyList.splice(elementIndex, 1);
          }
          // 新建一个属性字段的保存列表
          const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
            values: this.bpmnState.propertyList
          });
          this.updateElementExtensions(propertiesObject);
          this.resetAttributesList();
        })
        .catch(() => console.info("操作取消"));
    },
    /**保存方法 */
    async saveAttribute() {
      let validateStatus = await this.$refs["propertiesRef"].validate();
      if (!validateStatus) return; // 验证不通过直接返回
      switch (this.handleId) {
        case '1'://校验条件
          this.handlePropertiesSave(this.propertyForm)
          this.propertyFormModelVisible = false;
          break;
        case '2': // 前置处理 
          this.handlePropertiesSave(this.propertyPreForm)
          this.propertyPreFormModelVisible = false;
          break;
        case '3': // 后置处理
          this.handlePropertiesSave(this.propertyPostForm)
          this.propertyPostFormModelVisible = false;
          break;
        case '4': // 业务处理
          this.handlePropertiesSave(this.propertyBusiForm)
          this.propertyBusiFormModelVisible = false;
          break;
        default:
          break;
      }
      this.resetAttributesList();
    },
    /**保存属性 */
    handlePropertiesSave(from,) {
      const { name, value, } = from;
      const id = this.handleId;
      if (this.editingPropertyIndex !== -1) {
        window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.bpmnState.propertyList[this.editingPropertyIndex], {
          name,
          value,
          id,
        });
      } else {
        let isStop = false
        if (this.bpmnState.propertyList && this.bpmnState.propertyList.length > 0) {
          this.bpmnState.propertyList.forEach((element) => {
            if ((element.name === from.name) && (element.value === from.value) && (element.id === id)) {
              isStop = true
              return
            }
          });
          if (!isStop) {
            // 新建属性字段
            const newPropertyObject = window.bpmnInstances.moddle.create(`${this.prefix}:Property`, { name, value, id, });
            // 新建一个属性字段的保存列表
            const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
              values: this.bpmnState.propertyList.concat([newPropertyObject])
            });
            this.updateElementExtensions(propertiesObject);
          }
        } else {
          // 新建属性字段
          const newPropertyObject = window.bpmnInstances.moddle.create(`${this.prefix}:Property`, { name, value, id, });
          // 新建一个属性字段的保存列表
          const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
            values: this.bpmnState.propertyList.concat([newPropertyObject])
          });
          this.updateElementExtensions(propertiesObject);
        }
      }
    },
    /**更新bpmn元素的扩展属性 */
    updateElementExtensions(properties) {
      const extensions = window.bpmnInstances.moddle.create("bpmn:ExtensionElements", {
        values: this.otherExtensionList.concat([properties])
      });
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        extensionElements: extensions
      });
    }
  }
};
</script>

